package com.zlx.sharelive.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.HomeVideoBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.R;
import com.zlx.sharelive.fragment.ReviewFg;
import com.zlx.sharelive.fragment.SummaryFg;

import org.song.videoplayer.DemoQSVideoView;
import org.song.videoplayer.IVideoPlayer;
import org.song.videoplayer.PlayListener;
import org.song.videoplayer.QSVideo;
import org.song.videoplayer.floatwindow.FloatParams;
import org.song.videoplayer.media.AndroidMedia;
import org.song.videoplayer.media.BaseMedia;
import org.song.videoplayer.media.IjkMedia;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * 视频详情页面
 */
public class VideoDetailsAc extends BaseAc {

    @BindView(R.id.qs)
    DemoQSVideoView demoVideoView;
    @BindView(R.id.tv_synopsis)
    TextView tv_synopsis;
    @BindView(R.id.view_synopsis)
    View view_synopsis;
    @BindView(R.id.tv_comment)
    TextView tv_comment;
    @BindView(R.id.view_comment)
    View view_comment;

    private String id = "";
    private String title = "";
    private List<BaseFg> mFragment = new ArrayList<>();
    private String mp4;
    private float rate = 1.f;
    private boolean mute;
    private String url;
    private Class<? extends BaseMedia> decodeMedia;
    private List<TextView> mTextViewList = new ArrayList<>();
    private List<View> mViewList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.ac_video_details;
    }

    @Override
    public void initViews() {
        super.initViews();

        id = getIntent().getStringExtra("id");
        title = getIntent().getStringExtra("title");

        mTextViewList.clear();
        mTextViewList.add(tv_synopsis);
        mTextViewList.add(tv_comment);
        mViewList.clear();
        mViewList.add(view_synopsis);
        mViewList.add(view_comment);

        getHomeVideo();
        initFragment();
    }

    /**
     * 获取视频详情
     */
    private void getHomeVideo() {
        ApiUtil.getVideoApi().getHomeVideo(SPUtil.getToken(this), id).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<HomeVideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<HomeVideoBean> data) {
                if (data.getErrorCode() == 0) {
                    if (null != data.getData()) {
                        if (null != data.getData().getInfo()) {
                            if (data.getData().getInfo().size() > 0) {
                                setHomeVideo(data.getData().getInfo().get(0));
                            }
                        }
                    }
                }
            }
        }));
    }

    private void setHomeVideo(HomeVideoBean.InfoDTO infoDTO) {
        mp4 = infoDTO.getVideo();

        initVideo();
    }

    private void initFragment() {
        mFragment.clear();
        mFragment.add(SummaryFg.getInstance(title, id));
        mFragment.add(ReviewFg.getInstance(id));
        commitAllowingStateLoss(0);
    }

    private void commitAllowingStateLoss(int position) {
        hideAllFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(position + "");
        if (currentFragment != null) {
            transaction.show(currentFragment);
        } else {
            currentFragment = mFragment.get(position);
            transaction.add(R.id.frameLayout, currentFragment, position + "");
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 隐藏所有Fragment
     */
    private void hideAllFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mFragment.size(); i++) {
            Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(i + "");
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 初始化视频播放器
     */
    private void initVideo() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }
        demoVideoView.setLayoutParams(new FrameLayout.LayoutParams(-1, getResources().getDisplayMetrics().widthPixels * 9 / 16));
        //进入全屏的模式 0横屏 1竖屏 2传感器自动横竖屏 3根据视频比例自动确定横竖屏      -1什么都不做
        demoVideoView.enterFullMode = 3;
        //是否非全屏下也可以手势调节进度
        demoVideoView.isWindowGesture = true;
        demoVideoView.setPlayListener(new PlayListener() {
            int mode;

            @Override
            public void onStatus(int status) {//播放状态
                if (status == IVideoPlayer.STATE_AUTO_COMPLETE) {
                    demoVideoView.quitWindowFullscreen();//播放完成退出全屏
                }
            }

            @Override//全屏/普通/浮窗
            public void onMode(int mode) {
                this.mode = mode;
            }

            @Override
            public void onEvent(int what, Integer... extra) {
                //系统浮窗点击退出退出activity
                if (what == DemoQSVideoView.EVENT_CLICK_VIEW && extra[0] == R.id.help_float_close) {
                    if (demoVideoView.isSystemFloatMode()) {
                        finish();
                    }
                }
            }

        });

        play(mp4, AndroidMedia.class);
    }


    private void play(String url, Class<? extends BaseMedia> decodeMedia) {
        demoVideoView.release();
        demoVideoView.setDecodeMedia(decodeMedia);

        List<IjkMedia.Option> list = new ArrayList<>();
        list.add(new IjkMedia.Option(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", 1));

        demoVideoView.setUp(
                QSVideo.Build(url).option(list).build()
        );
        this.url = url;
        this.decodeMedia = decodeMedia;
    }

    public void 静音(View v) {
        demoVideoView.setMute(mute = !mute);
        ((Button) v).setText(mute ? "静音 ON" : "静音 OFF");
    }


    public void 倍速(View v) {
        rate += 0.25f;
        if (rate > 2) {
            rate = 0.25f;
        }

        if (!demoVideoView.setSpeed(rate)) {
            Toast.makeText(this, "该解码器不支持", Toast.LENGTH_SHORT).show();
            rate = 1f;
        }
        ((Button) v).setText("倍速 X" + rate);
    }

    //android:launchMode="singleTask" 根据自己需求设置
    public void 系统浮窗(View v) {
        if (demoVideoView.getCurrentMode() == IVideoPlayer.MODE_WINDOW_FLOAT_ACT) {
            return;
        }
        enterFloat(true);
        ((Button) v).setText(demoVideoView.isWindowFloatMode() ? "退出浮窗" : "系统浮窗");
    }

    public void 界面内浮窗(View v) {
        if (demoVideoView.getCurrentMode() == IVideoPlayer.MODE_WINDOW_FLOAT_SYS) {
            return;
        }
        enterFloat(false);
        ((Button) v).setText(demoVideoView.isWindowFloatMode() ? "退出浮窗" : "界面内浮窗");
    }


    public void 销毁(View v) {
        demoVideoView.release();
    }


    //返回键
    @Override
    public void onBackPressed() {
        //全屏和系统浮窗不finish
        if (demoVideoView.onBackPressed()) {
            if (demoVideoView.isSystemFloatMode())
            //系统浮窗返回上一界面 android:launchMode="singleTask"
            {
                moveTaskToBack(true);
            }
            return;
        }
        super.onBackPressed();
    }

    //进入浮窗
    private void enterFloat(boolean isSystemFloat) {
        FloatParams floatParams = demoVideoView.getFloatParams();
        if (floatParams == null) {
            floatParams = new FloatParams();
            floatParams.x = 0;
            floatParams.y = 0;
            floatParams.w = getResources().getDisplayMetrics().widthPixels * 3 / 4;
            floatParams.h = floatParams.w * 9 / 16;
            floatParams.round = 30;
            floatParams.fade = 0.8f;
            floatParams.canMove = true;
            floatParams.canCross = false;
        }
        floatParams.systemFloat = isSystemFloat;

        if (demoVideoView.isWindowFloatMode()) {
            demoVideoView.quitWindowFloat();
        } else {
            if (!demoVideoView.enterWindowFloat(floatParams)) {
                Toast.makeText(this, "没有浮窗权限", Toast.LENGTH_LONG).show();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, 0);
                }
            }
        }
        if (demoVideoView.isSystemFloatMode()) {
            onBackPressed();
        }
    }


    //=======================以下生命周期控制=======================

    private boolean playFlag;//记录退出时播放状态 回来的时候继续播放
    private int position;//记录销毁时的进度 回来继续该进度播放
    private Handler handler = new Handler();

    @Override
    public void onResume() {
        super.onResume();
        if (playFlag) {
            demoVideoView.play();
        }
        handler.removeCallbacks(runnable);
        if (position > 0) {
            demoVideoView.seekTo(position);
            position = 0;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (demoVideoView.isSystemFloatMode()) {
            return;
        }
        //暂停
        playFlag = demoVideoView.isPlaying();
        demoVideoView.pause();
    }


    @Override
    public void onStop() {
        super.onStop();
        if (demoVideoView.isSystemFloatMode()) {
            return;
        }
        //进入后台不马上销毁,延时15秒
        handler.postDelayed(runnable, 1000 * 15);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();//销毁
        if (demoVideoView.isSystemFloatMode()) {
            demoVideoView.quitWindowFloat();
        }
        demoVideoView.release();
        handler.removeCallbacks(runnable);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (demoVideoView.getCurrentState() != IVideoPlayer.STATE_AUTO_COMPLETE) {
                position = demoVideoView.getPosition();
            }
            demoVideoView.release();
        }
    };

    //=======================以下其他逻辑=======================

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 & resultCode == RESULT_OK) {
            mp4 = data.getData().toString();
            Toast.makeText(this, mp4, Toast.LENGTH_LONG).show();
            play(mp4, decodeMedia);
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setPrimaryClip(ClipData.newPlainText("text", mp4));
        }
    }


    @OnClick({R.id.iv_back, R.id.ll_synopsis, R.id.ll_comment})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.ll_synopsis://简介
                commitAllowingStateLoss(0);
                setTextViewColor(0);
                break;
            case R.id.ll_comment:
                commitAllowingStateLoss(1);
                setTextViewColor(1);
                break;
            case R.id.iv_back:
                finish();
                break;
            default:

                break;
        }
    }

    private void setTextViewColor(int position) {
        for (int j = 0; j < mTextViewList.size(); j++) {
            if (position == j) {
                mViewList.get(position).setVisibility(View.VISIBLE);
            } else {
                mViewList.get(j).setVisibility(View.INVISIBLE);
            }
        }
    }


}
